/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csse3004.GD;

import csse3004.GD.DA.LoginDA;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 *
 * @author David Bullock 42062222
 */
public class changePasswordValidator implements Validator {

    LoginService service = new LoginDA();
    protected final Log log = LogFactory.getLog(getClass());

    public boolean supports(Class type) {
        return changePasswordController.class.equals(type) || changePassword.class.equals(type);
    }

    public void validate(Object o, Errors errors) {
        changePassword pass = (changePassword) o;
        String current = pass.getCurrent();
        String p1 = pass.getPass1();
        String p2 = pass.getPass2();
        if (pass.getUserName().equals("")) {
            errors.rejectValue("userName", "error.not-specified", null, "You aren't logged in, come back when you have some credentials you skallywag!");
        } else {
            if (current.isEmpty()) {
                errors.rejectValue("current", "error.not-specified", null, "Please enter your password");
            }
            if (p1.isEmpty()) {
                errors.rejectValue("pass1", "error.not-specified", null, "Password Required.");
            } else if (p2.isEmpty()) {
                errors.rejectValue("pass2", "error.not-specified", null, "Please re-enter your password.");
            }

            if (!p1.equals(p2)) {
                errors.rejectValue("pass1", "error.not-specified", null, "Passwords do not match");
            }
            if(errors.getErrorCount()==0){
                if (!service.checkAccountDetails(pass.getUserName(), current)){
                    errors.rejectValue("current", "error.not-specified", null, "Your password is incorrect");
                }
            }
            

        }
    }
}
